package com.fowo.api.service.handleWork;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReflectUtil;
import com.fowo.api.inventory.entity.Inventory;
import com.fowo.api.inventory.mapper.InventoryMapper;
import com.fowo.api.inventory.model.*;
import com.fowo.api.inventory.model.form.InventoryExchangeFormVo;
import com.fowo.api.inventory.service.InventoryBusinessService;
import com.fowo.api.mapper.InventoryListMapper;
import com.fowo.api.model.inventory.list.InventoryListBeginInventoryAction;
import com.fowo.api.model.inventory.list.InventoryListVo;
import com.fowo.api.model.inventory.list.subtable.InventoryListSubtableItemVo;
import com.fowo.api.service.InventoryListSubtableService;
import com.fowo.api.service.impl.InventoryListServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Component
public class InventoryListBeginInventory implements InventoryListBeginInventoryAction {

    @Resource
    private InventoryMapper inventoryMapper;
    @Resource
    private InventoryListServiceImpl inventoryListService;
    @Resource
    private InventoryBusinessService inventoryBusinessService;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void run(Long id) throws Exception {
        InventoryListVo inventoryList = inventoryListService.getVoById(id);
        Assert.notNull(inventoryList,"盘点单不存在");
        Assert.isTrue(inventoryList.getStatus().equals("0") || inventoryList.getStatus().equals("1"),"当前单据状态不可进行此操作！");

//        InventoryListSubtableSearchParamPo generateInventoryDetailsSearchParamPo = new InventoryListSubtableSearchParamPo();
//        generateInventoryDetailsSearchParamPo.setParentInventoryList(id);
//        List<InventoryListSubtableItemVo> subList = inventoryListSubtableService.search(generateInventoryDetailsSearchParamPo);
        List<InventoryListSubtableItemVo> subList = inventoryList.getGenerateInventoryDetails();
        //查询是否有锁定库存
        final Optional<InventoryListSubtableItemVo> any = subList.stream().filter(sub -> getInventory(sub, inventoryList.getWarehouseStock()).compareTo(new BigDecimal(0)) > 0).findAny();
        InventoryListSubtableItemVo inventoryListSubtableItemVo = null;
        if(any != null && any.isPresent()){
            inventoryListSubtableItemVo = any.get();
        }

        if (inventoryListSubtableItemVo != null) {
            inventoryList.setStatus("0");
        }else{
//            lockInventory(subList,inventoryList.getWarehouseStock());
            // 锁仓库库存
            InventoryExchangeFormVo warehouseFormVo = prepareLockWarehouse(inventoryList);
            inventoryBusinessService.exchange(warehouseFormVo);
            // 锁仓位库存
            InventoryExchangeFormVo formVo = prepareLockInventory(inventoryList);
            inventoryBusinessService.exchange(formVo);

            inventoryList.setStatus("2");
        }
//        inventoryListMapper.updateById(inventoryList);
        inventoryListService.update(inventoryList);
    }

    /**
     * 查询是否有锁定库存
     * @param subtableItemVo
     * @param stockId
     * @return
     */
    public BigDecimal getInventory(InventoryListSubtableItemVo subtableItemVo, Long stockId){
        SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
        inventoryItem.setId(subtableItemVo.getTradeName());

        InventoryStorageVo inventoryStorageVo = new InventoryStorageVo();
        inventoryStorageVo.setStockId(stockId);
        inventoryStorageVo.setItem(inventoryItem);
        inventoryStorageVo.setShopId(subtableItemVo.getShop() == null ? null : subtableItemVo.getShop().toString());
        inventoryStorageVo.setFnSku(subtableItemVo.getFnsku());

        List<Inventory> inventoryList =inventoryMapper.selectByStorageOne(inventoryStorageVo);
        if (CollectionUtils.isNotEmpty(inventoryList)){
            Inventory inventory = inventoryList.get(0);
            return inventory.getLockQty() == null ? new BigDecimal(0) : inventory.getLockQty();
        }else {
            return new BigDecimal(0);
        }
    }


    /**
     * 准备用于 锁库存 的参数
     */
    protected InventoryExchangeFormVo prepareLockInventory(InventoryListVo vo) throws Exception {
        InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
        if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
            formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
        }
        formVo.setFrom(TargetTypeEnum.Normal);
        formVo.setTo(TargetTypeEnum.Normal);
        formVo.setFormNum(vo.getInventoryNumber());
        formVo.setFormOperator(vo.getLastUpdateUser().toString());
        formVo.setDocumentType("盘点锁库存");
        if(ObjectUtils.isEmpty(vo.getWarehouseStock())){
            throw new Exception("出仓库 为空");
        }
        formVo.setFromStockId(vo.getWarehouseStock());
        if(ObjectUtils.isEmpty(vo.getWarehouseStock())){
            throw new Exception("入仓库 为空");
        }
        formVo.setToStockId(vo.getWarehouseStock());
        formVo.setModel(PatternEnum.FIFO);
        for(InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryItem.setId(inventoryListSubtable.getTradeName());
            InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
            exchangeItem.setItem(inventoryItem);
            exchangeItem.setQty(String.valueOf(inventoryListSubtable.getInventory()).equals("null")?BigDecimal.valueOf(0):BigDecimal.valueOf(inventoryListSubtable.getInventory()));
            exchangeItem.setShopId(String.valueOf(inventoryListSubtable.getShop()).equals("null")? null:String.valueOf(inventoryListSubtable.getShop()));
            exchangeItem.setFnSku( String.valueOf(inventoryListSubtable.getFnsku()).equals("null")? null:String.valueOf(inventoryListSubtable.getFnsku()));
            Map<Long,Integer> binIds=new HashMap<>();
            binIds.put(inventoryListSubtable.getShippingSpace(),Integer.parseInt(String.valueOf(inventoryListSubtable.getInventory()).equals("null")? "0":String.valueOf(inventoryListSubtable.getInventory())));
            exchangeItem.setFromBinIds(binIds);
            Map<Long,Integer> toBinIds=new HashMap<>();
            toBinIds.put(inventoryListSubtable.getShippingSpace(),Integer.parseInt(String.valueOf(inventoryListSubtable.getInventory()).equals("null")? "0":String.valueOf(inventoryListSubtable.getInventory())));
            exchangeItem.setToBinIds(toBinIds);
            exchangeItem.setFromBinIdsType(TargetTypeEnum.Normal);
            exchangeItem.setToBinIdsType(TargetTypeEnum.Lock);
            exchangeItem.setCustomId(vo.getId());
            exchangeItem.setCustomBdId(inventoryListSubtable.getId());
            formVo.add(exchangeItem);
        }
        return formVo;
    }

    /**
     * 准备用于 锁库存_仓库 的参数
     */
    protected InventoryExchangeFormVo prepareLockWarehouse(InventoryListVo vo)
            throws Exception {
        InventoryExchangeFormVo formVo = new InventoryExchangeFormVo();
        if (ReflectUtil.hasField(InventoryListVo.class, "remark")) {
            formVo.setRemark(Convert.toStr(ReflectUtil.getFieldValue(vo, "remark")));
        }
        formVo.setFrom(TargetTypeEnum.Normal);
        formVo.setTo(TargetTypeEnum.Lock);
        formVo.setFormNum(vo.getInventoryNumber());
        formVo.setDocumentType("盘点锁库存");
        if (ObjectUtils.isEmpty(vo.getLastUpdateUser())) {
            throw new Exception("关联制单人为空");
        }
        formVo.setFormOperator(vo.getLastUpdateUser().toString());
        if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
            throw new Exception("出仓库 为空");
        }
        formVo.setFromStockId(vo.getWarehouseStock());
        if (ObjectUtils.isEmpty(vo.getWarehouseStock())) {
            throw new Exception("入仓库 为空");
        }
        formVo.setToStockId(vo.getWarehouseStock());
        formVo.setModel(PatternEnum.FIFO);
        for (InventoryListSubtableItemVo inventoryListSubtable : vo.getGenerateInventoryDetails()) {
            SimpleInventoryItem inventoryItem = new SimpleInventoryItem();
            inventoryItem.setId(inventoryListSubtable.getTradeName());
            InventoryExchangeVo exchangeItem = new InventoryExchangeVo();
            exchangeItem.setItem(inventoryItem);
            exchangeItem.setQty(
                    String.valueOf(inventoryListSubtable.getInventory()).equals("null")
                            ? BigDecimal.valueOf(0)
                            : BigDecimal.valueOf(inventoryListSubtable.getInventory())
            );
            exchangeItem.setShopId(
                    String.valueOf(inventoryListSubtable.getShop()).equals("null")
                            ? null
                            : String.valueOf(inventoryListSubtable.getShop())
            );
            exchangeItem.setFnSku(
                    String.valueOf(inventoryListSubtable.getFnsku()).equals("null")
                            ? null
                            : String.valueOf(inventoryListSubtable.getFnsku())
            );
            exchangeItem.setCustomId(vo.getId());
            exchangeItem.setCustomBdId(inventoryListSubtable.getId());
            formVo.add(exchangeItem);
        }
        return formVo;
    }

}
